package com.bi.design.controller;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.bi.design.dto.LoginDTO;
import com.bi.design.entity.SysUser;
import com.bi.design.pojo.TokenTools;
import com.bi.design.service.SysUserService;
import com.bi.design.tools.ApiResult;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;
import java.util.Objects;


@Slf4j
@RestController
@RequiredArgsConstructor
@RequestMapping("/")
public class LoginController {
    private final SysUserService sysUserService;
    private final PasswordEncoder passwordEncoder;


    /**
     * 登录接口
     */
    @PostMapping(value = "login")
    public ApiResult<Object> login(@Validated @RequestBody LoginDTO loginDto) {
        // 先检验是否登录
        String username = loginDto.getAccount();
        String password = loginDto.getPassword();
        SysUser user = sysUserService.getOne(Wrappers.lambdaQuery(SysUser.class).eq(SysUser::getAccount, username));
        if (Objects.isNull(user) || user.getDisabled() || user.getDeleted()) {
            return ApiResult.failed("该用户不存在或者已被删除禁用！");
        }
        // [4] 数据库用户的密码，一般都是加密过的
        String encryptedPassword = user.getPassword();
        // 根据加密算法加密用户输入的密码，然后和数据库中保存的密码进行比较
        if (!this.passwordEncoder.matches(password, encryptedPassword)) {
            return ApiResult.failed("输入账号或密码不正确");
        }
        Map<String, Object> tokenInfo = new HashMap<>(2);
        tokenInfo.put("userInfo", user);
        // TODO 此处重写生成令牌
        tokenInfo.put("token", TokenTools.saveToken());
        return ApiResult.ok(tokenInfo);
    }

}
